package com.hoangkien.DAO;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.hoangkien.entity.UserEntity;

public class UserDAO {
	private static final String TAG = "UserDAO";
	private final SQLiteDatabase db;  //co bien final thi phai co ham khoi tao chua bien final
	
	public UserDAO(SQLiteDatabase db) {
		super();
		this.db = db;
	}
	
	public long insertUser(UserEntity userEntity){
		ContentValues value = new ContentValues();
//		value.put(UserScheme.ID, userEntity.getId());
		value.put(UserScheme.KIND, userEntity.getKind());
		value.put(UserScheme.PERMALINK, userEntity.getPermalink());
		value.put(UserScheme.USERNAME, userEntity.getUsername());
		value.put(UserScheme.LAST_MODIFIED, userEntity.getLast_modified());
		value.put(UserScheme.URI, userEntity.getUri());
		value.put(UserScheme.PERMALINK_URL, userEntity.getPermalink_url());
		if(db.insert(UserScheme.TABLE_USER_NAME, null, value) == -1){
			Log.e(TAG,"Bug insert user");
		} else {
			Log.e(TAG,"Successfully insert user");
		}
		return 0;
	}
	
	public ArrayList<UserEntity> getAllUser(){
		ArrayList<UserEntity> listUser = new ArrayList<UserEntity>();
		String query = "select * from "+UserScheme.TABLE_USER_NAME;
		Cursor cursor = db.rawQuery(query, null);
		if(cursor.moveToFirst()) {
			do {
				UserEntity userEntity = new UserEntity();
				userEntity.setId(cursor.getInt(0));
				userEntity.setKind(cursor.getString(1));
				userEntity.setPermalink(cursor.getString(2));
				userEntity.setUsername(cursor.getString(3));
				userEntity.setLast_modified(cursor.getString(4));
				userEntity.setUri(cursor.getString(5));
				userEntity.setPermalink_url(cursor.getString(6));
				userEntity.setAvatar_url(cursor.getString(7));
				listUser.add(userEntity);
			} while(cursor.moveToNext());
		}
		return listUser;
		
	}
	
	public long deleteTableUser(){
		long result = 0;
		try {
			result = db.delete(UserScheme.TABLE_USER_NAME, null, null);
			Log.e(TAG,"delete table user successfully");
		} catch (Exception e) {
			Log.e(TAG,"delete table user fail");
		}
		return result;	
	}
	
}
